package com.nt.train.service.context;
import com.nt.train.dto.Member;
import com.nt.train.service.Strategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
 * 会员策略管理器
 * @author hlf
 * @version 1.0
 * @date 2022/8/5 9:23
 */
@Component
public class StrategyContext {

    /**
     *使用线程安全的ConcurrentHashMap存储所有实现Strategy接口的Bean
     *key:beanName
     *value：实现Strategy接口Bean
     */
    private final Map<String, Strategy> strategyMap = new ConcurrentHashMap<>();

    /**
     * 注入所有实现了Strategy接口的Bean
     * @param strategyMap
     */
    @Autowired
    public StrategyContext(Map<String, Strategy> strategyMap) {
        this.strategyMap.clear();
        strategyMap.forEach((k, v)-> this.strategyMap.put(k, v));
    }

    /**
     * 计算价格
     * @param member  会员信息
     * @return       价格
     */
    public BigDecimal calculatePrice(Member member) {
        //在这里要捕捉异常，或者是做相应处理，因为如果找不到service名字
        //会报错，也就是找不到对应的策略
        if(!StringUtils.isEmpty(member.getMemberLevel())){
            return strategyMap.get(member.getMemberLevel()).calculatePrice(member);
        }
        return null;
    }
}